<template>
  <div>
    <!-- 条件搜索框 -->
    <div class="search-div">
      <el-form label-width="70px" size="small">
        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌">
              <el-select
                class="m-2"
                placeholder="选择品牌"
                size="small"
                style="width: 100%"
                v-model="searchObj.brandId"
              >
                <el-option
                  v-for="item in brandList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类">
              <el-cascader
                v-model="categoryIds"
                :props="categoryProps"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="display:flex">
          <el-button type="primary" size="small" @click="fetchData">
            搜索
          </el-button>
          <el-button size="small" @click="reset">重置</el-button>
        </el-row>
      </el-form>
    </div>

    <div class="tools-div">
      <el-button type="success" size="small" @click="dialogVisible = true">
        添 加
      </el-button>
    </div>
    <!-- 数据表格 -->
    <el-table :data="list" style="width: 100%">
      <el-table-column prop="categoryName" label="分类" />
      <el-table-column prop="brandName" label="品牌" />
      <el-table-column prop="brandLogo" label="品牌图标" #default="scope">
        <img :src="scope.row.brandLogo" width="50" />
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" align="center" width="200" #default="scope">
        <el-button
          type="primary"
          size="small"
          @click="handleShowEditDialog(scope.row)"
        >
          修改
        </el-button>
        <el-button type="danger" size="small" @click="handleDelete(scope.row)">
          删除
        </el-button>
      </el-table-column>
    </el-table>

    <div style="margin-top: 80px;">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[1, 2, 3, 4, 5]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="fetchData"
        @current-change="fetchData"
      />
    </div>
    <!-- 新增/修改 分类品牌对话框 -->
    <div>
      <el-dialog v-model="dialogVisible" title="添加或修改" width="30%">
        <el-form label-width="120px">
          <el-form-item label="品牌">
            <el-select
              v-model="categoryBrand.brandId"
              class="m-2"
              placeholder="选择品牌"
              size="small"
            >
              <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="分类">
            <el-cascader v-model="categoryIds2" :props="categoryProps" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSaveOrUpdate">
              提交
            </el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import {
  GetCategoryBrandPage,
  DeleteCategoryBrandById,
  GetCategoryBrandById,
  UpdateCategoryBrandById,
  SaveCategoryBrand,
} from '@/api/categoryBrand'
import { GetAllBrand } from '@/api/brand'
import { GetCategoriesByPid } from '@/api/category'
import { ElMessage } from 'element-plus'
//更新删除
const handleShowEditDialog = row => {
  categoryBrand.value = { ...row }
  dialogVisible.value = true
}
const handleUpdate = async () => {
  if (categoryIds.value && categoryIds2.value.length === 3) {
    categoryBrand.value.categoryId = categoryIds2.value[2]
  }
  if (categoryBrand.value.brandId && categoryBrand.value.categoryId) {
    await UpdateCategoryBrandById(categoryBrand.value)
    ElMessage.success('更新成功')
    fetchData()
  } else {
    ElMessage.warning('请选中品牌或者分类')
  }
  dialogVisible.value = false
}
const handleDelete = async row => {
  await DeleteCategoryBrandById(row.id)
  ElMessage.success('删除成功')
  fetchData()
}

//==== 新增修改对话框
const categoryBrand = ref({}) //新增或修改分类品牌对象
const dialogVisible = ref(false)
const handleSaveOrUpdate = () => {
  if (categoryBrand.value.id) {
    //更新
    handleUpdate()
  } else {
    //新增
    handleSave()
  }
}
const handleSave = async () => {
  //   console.log(categoryBrand.value)
  if (categoryIds.value && categoryIds2.value.length === 3) {
    categoryBrand.value.categoryId = categoryIds2.value[2]
  }
  if (categoryBrand.value.brandId && categoryBrand.value.categoryId) {
    await SaveCategoryBrand(categoryBrand.value)
    ElMessage.success('新增成功')
  } else {
    ElMessage.warning('请选中品牌或者分类')
  }
  dialogVisible.value = false
}

//条件搜索框
const brandList = ref([])
const categoryIds = ref([])
const categoryIds2 = ref([])
const categoryList = ref([]) //分类列表：因为使用了懒加载，所以初始化只查询一级分类列表
const categoryProps = {
  expandTrigger: 'click',
  lazy: true,
  value: 'id',
  label: 'name',
  //级联选择器懒加载的事件函数
  lazyLoad: async (node, resolve) => {
    if (typeof node.value == 'undefined') node.value = 0
    //鼠标悬停时触发 需要查询鼠标悬停节点的下一级
    console.log(node.value)
    const { data } = await GetCategoriesByPid(node.value)
    data.forEach(category => {
      //给每个分类添加leaf属性值：设置它是否为叶子节点
      category.leaf = !category.hasChildren
    })
    //解析渲染数据
    resolve(data)
  },
  //leaf表示是否为叶子节点
  leaf: 'leaf',
}
const searchObj = ref({})
//表格数据
const list = ref([])
//分页导航
const pageNum = ref(1)
const pageSize = ref(3)
const total = ref(0)
const fetchData = async () => {
  //条件查询分页数据时，判断，如果分类id集合不为空 且长度为3 表示级联选择器选择了 分类id
  //获取三级分类id作为条件到后端查询
  if (categoryIds.value && categoryIds.value.length === 3) {
    console.log(categoryIds.value)

    searchObj.value.categoryId = categoryIds.value[2]
  }

  const { data } = await GetCategoryBrandPage(
    pageNum.value,
    pageSize.value,
    searchObj.value
  )
  list.value = data.list
  total.value = data.total
}
onMounted(async () => {
  fetchData()

  const { data } = await GetAllBrand()
  brandList.value = data
})

//重置按钮事件函数
const reset = () => {
  searchObj.value = {}
  pageNum.value = 1
  pageSize.value = 3
  fetchData()
}
</script>
<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
</style>
